package com.smile.cloud.order.service;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author LGC
 * @date 2021/8/17 13:43
 * @copyright 2021 mofang. All rights reserved
 */
@Slf4j
@Component
public class DelayOrderListener implements MessageListenerConcurrently {
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (int i = 0; i < msgs.size(); i++) {
                MessageExt messageExt = msgs.get(i);
                String topic = messageExt.getTopic();
                String tags = messageExt.getTags();
                String body = new String(messageExt.getBody(), StandardCharsets.UTF_8);
                log.info("{} receive MQ消息 topic={}, tags={}, msg={},messageExt={}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), topic, tags, body, messageExt);
                if (DelayConsumer.TOPIC_ORDER_DELAY.equals(messageExt.getTopic())) {
                    // todo 这里要确保消息只被消费一次,可以参考 smile-points-service积分
                    // todo 根据订单编号查看订单是否已支付
                    // todo 未支付发送消息 关闭订单，释放库存
                    log.info("根据订单编号查看订单是否已支付");
                    log.info("未支付发送消息 关闭订单，释放库存。。。");

                    log.info("完成关闭订单，释放库存...");
                }
            }
        } catch (Exception e) {
            log.error("处理订单数据，准备关闭订单，释放库存发生异常。{0}", e);
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
